package com.xiaoniu.douyinvideo.apps

import android.text.TextUtils
import org.jsoup.Jsoup

/**
 * @author zhaohe
 * @date 2021/3/26 15:11
 * @desc 抖音app
 */
class TikTokVideo(var htmlUrl: String?) : VideoApp() {
    public override fun htmlUrl(): String? {
        return htmlUrl
    }

    public override fun parseHtml(htmlCode: String?): Pair<String, String>? {
        if (TextUtils.isEmpty(htmlCode)) {
            return null
        }
        //        <div class="video-container"><video class="video-player hide" src=""><div>
        val videoContainers = Jsoup.parse(htmlCode).getElementsByClass("video-container")
        if (videoContainers == null || videoContainers.isEmpty()) {
            return null
        }
        val videos = videoContainers.get(0).getElementsByTag("video")
        if (videos == null || videos.isEmpty()) {
            return null
        }
        //获取url
        var videoUrl = videos.get(0).attr("src") ?: ""
        var finalVideoUrl: String = videoUrl
        if (!TextUtils.isEmpty(videoUrl)) {
            //拼接前缀
            if (!videoUrl.startsWith("http")) {
                videoUrl = "https://www.douyin.com" + videoUrl
            }
            //重定向到最终url
            val transformUrl = videoUrlTransform(videoUrl) ?: videoUrl
            finalVideoUrl = getRealUrl(transformUrl.replace("720p", "1080p")) ?: "" //1080p
            if (finalVideoUrl.isEmpty()){
                finalVideoUrl = getRealUrl(transformUrl) ?: videoUrl
            }
        }
        return Pair(videoUrl, finalVideoUrl)
    }

    public override fun videoUrlTransform(videoUrl: String?): String? {
        if (TextUtils.isEmpty(videoUrl)) {
            return null
        }
        //playwm 有水印   play无水印
        return videoUrl!!.replace("playwm", "play")
    }
}
